import router from './router'
import axios from 'axios'

const baseUrl = process.env.NODE_ENV === 'development' ? 'https://192.168.0.181:8101/login':'http://10.3.208.111:9085/tlgaj_st/portal/token/valid?token=&returnURL=';
const url = process.env.NODE_ENV === 'development' ? 'https://www.easy-mock.com/mock/5b742307ee973f101f9e9775/datashow/platform/common/validToken':'/platform/common/validToken';

router.beforeEach((to, from, next) => {
  let token = getUrlParam('token');

  if(token == null||token == ''){
    // 判断是否有token
    if (getCookie('token')) { 
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        next()
      }
    } else {
      window.location.href = baseUrl + window.location.href;
    }
  }else{
    axios.get(url+"?token="+token).then(function(res){
      if(res.data){
        let exp = new Date();
        exp.setTime(exp.getTime() + 30*60*1000);
        document.cookie = 'token='+ token + ';expires='+ exp.toGMTString();
      }else{
        window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
      }
      // 判断是否有token
      if (to.path === '/login') {
        next({ path: '/' });
      } else {
        next()
      }
    }).catch(function(){
      window.location.href = baseUrl + window.location.href.replace(window.location.search,'');
    })
  }
});

function getCookie(name) {
  let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
    return unescape(arr[2]);
  else
    return null;
};
// 获取url参数方法
function getUrlParam(name) { 
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
  var r = window.location.search.substr(1).match(reg); 
  if (r != null) return unescape(r[2]); return null; 
} 
